import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'

// axios 配置
// axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true;
axios.defaults.headers = {
    'Content-Type' : 'application/json;charset=UTF-8',
}
if (store.getters.token) {
    axios.defaults.headers = {
        'X-Token':getToken()
    }
}

//返回状态判断
axios.interceptors.response.use(response =>{
    const res = response.data
    if (res.code && res.code === -1) {
        if(res.data){
            return Promise.reject(Message.error(res.data.message))
        }else{
            return response;
        }
    } else {
        return response;
    }
}, (error) => {
    const response = error.response;
    if (response.status === 401) {
        console.log("401了，这里")
        MessageBox.confirm('登录已过期，请重新登录', '登录失效', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            store.dispatch('user/resetToken').then(() => {
                location.reload()
            });
        })
    }else{
        return Promise.reject( Message.error(response.data.message))
    }
    // return Promise.reject(new Error(response.data.message || 'Error'))
});

export function postFetch(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
               reject(error)
            })
    })
}
export function getFetch(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params:params})
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
               reject(error)
            })
    })
}
